package com.quanquan.user.service;


import com.quanquan.user.entity.PosOrder;
import com.quanquan.user.entity.User;
import com.quanquan.user.repository.PosOrderRepository;
import com.quanquan.user.repository.UserRepository;
import com.quanquan.user.request.IntegralDetailsRequestBody;
import com.quanquan.user.request.PosOrderRequestBody;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.UUIDGenerator;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PosOrderService {


    @Autowired
    private IntegralTradingDetailsService integralTradingDetailsService;


    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PosOrderRepository posOrderRepository;

    public PosOrder createPosOrder(PosOrderRequestBody requestBody){

        PosOrder posOrder = new PosOrder();
        //通过映射关系来赋值 //TODO 断点看一下
        BeanUtils.copyProperties(requestBody, posOrder);
        posOrder.setId(requestBody.getTicketNum());
        posOrder.setCreateTime(DateUtils.currentDate());
        posOrder.setApplicationStatus("payment");
        posOrderRepository.saveAndFlush(posOrder);
        return posOrder;
    }

    public PosOrder findPosOrder(String ticketNum){
        PosOrder posOrder = posOrderRepository.findByTicketNum(ticketNum);
        return posOrder;
    }

    public Map refund(String userId, String receivePoint, String ticketNum) {
        Map map = new HashMap<>();
        map.put("integral","-"+receivePoint);
        List<User> users = userRepository.findUserByIdAndRemove(userId, 0);
        if(users.size()<=0){
            return null;
        }
        User user = users.get(0);
        Integer integral = user.getIntegral();
       Integer total= integral-Integer.valueOf(receivePoint);
       if(total<=0){
           createIntegralRecord(ticketNum, user, integral);
           map.put("totalIntegral", 0);
       }else {
           createIntegralRecord(ticketNum, user, Integer.valueOf(receivePoint));
           map.put("totalIntegral", total);
       }
        userRepository.save(user);

        return map;
    }

    private void createIntegralRecord(String ticketNum, User user, Integer integral) {
        //生成积分记录
        IntegralDetailsRequestBody requestBody = new IntegralDetailsRequestBody();
        requestBody.setIntegralPoint(String.valueOf(integral));
        requestBody.setUserId(user.getId());
        requestBody.setTradeAction(1);
        requestBody.setConsumeType("pos");
        requestBody.setSource("pos");
        requestBody.setForeignKeyId(ticketNum);
        requestBody.setOrderNum(ticketNum);
        requestBody.setTradingContent("pos退款，退还积分");
        integralTradingDetailsService.createIntegralDetails(requestBody);
    }
}
